#include "scanner/episode_name_parser.h"

#include <sstream>

namespace Tvimeg
{
	EpisodeNameParser::EpisodeNameParser(void)
		:	season(0), episode(0)
	{
	}

	bool EpisodeNameParser::Parse(const std::string& name)
	{
		bool inNumber = false, hasSeason = false, hasEpisode = false;
		int numberStart = 0;
		char lastCharacter = 0;

		const std::size_t length = name.length();
		for (std::size_t index = 0; index < length && (!hasSeason || !hasEpisode); ++index)
		{
			const char character = name[index];

			if (character >= '0' && character <= '9')
			{
				if (!inNumber)
				{
					numberStart = index;
				}
				inNumber = true;
			}
			else
			{
				if (inNumber)
				{
					if (lastCharacter == 's' || lastCharacter == 'S')
					{
						season = GetInt(name, numberStart, index - 1);
						hasSeason = true;
					}
					else if (lastCharacter == 'e' || lastCharacter == 'E' || lastCharacter == 'x' || lastCharacter == 'X')
					{
						episode = GetInt(name, numberStart, index - 1);
						hasEpisode = true;
					}
					else if (character == 'x' || character == 'X')
					{
						season = GetInt(name, numberStart, index - 1);
						hasSeason = true;
					}
				}

				lastCharacter = character;
				inNumber = false;
			}
		}

		return hasSeason && hasEpisode;
	}

	int EpisodeNameParser::GetInt(const std::string& string, const int startIndex, const int endIndex) const
	{
		std::stringstream stream(string.substr(startIndex, endIndex - startIndex + 1));

		int temp = 0;
		stream >> temp;
		return temp;
	}
}
